package com.sk.z.khk.googleplace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GooglePlaces {
	private String googlePlacesURL = "https://maps.googleapis.com/maps/api/place/search/json";
	private GPURLParam param;
	private InputStreamReader isr = null;
	private BufferedReader br = null;

	public void setURLParam(GPURLParam param) {
		this.param = param;
	}

	public GPURLParam getURLParam() {
		return param;
	}

	public URL makeURL(GPURLParam param) {
		if (param == null)
			return null;
		try {
			return new URL(googlePlacesURL + "?" + param.toString());
		} catch (MalformedURLException e) {
		}
		return null;
	}

	public String getPlacesAsJsonString(URL url) {
		URLConnection connection;
		StringBuffer sb = new StringBuffer();
		try {
			connection = url.openConnection();
			connection.setDoOutput(false);
			isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
			br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(isr, br);
		}
		return sb.toString();
	}

	public String getPlacesAsJsonString() {
		return getPlacesAsJsonString(param);
	}

	public String getPlacesAsJsonString(GPURLParam param) {
		URL url = makeURL(param);
		if (url == null)
			return null;
		return getPlacesAsJsonString(url);
	}

	private void close(InputStreamReader isr, BufferedReader br) {
		try {
			isr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
